package ext.tianma.part.addressee;

import java.io.File;
import java.rmi.RemoteException;
import java.util.List;

import ext.com.iba.IBAUtil;
import ext.tianma.util.PropertiesUtil;
import ext.tianma.workflow.BomWorkFlowUtil;
import wt.fc.ObjectReference;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.fc.WTObject;
import wt.org.WTUser;
import wt.part.WTPart;
import wt.part.WTPartConfigSpec;
import wt.part.WTPartStandardConfigSpec;
import wt.project.Role;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.team.Team;
import wt.team.TeamManaged;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.config.ConfigHelper;
import wt.vc.views.View;
import wt.workflow.engine.WfProcess;

public class BLUUserUtil {
	
	private static String configFilePath = "codebase" + File.separator + "ext" + File.separator + "tianma"
			+ File.separator + "part" +File.separator + "addressee" +File.separator + "config" + File.separator + "addressee.properties";


	private static String internal_value = "RECIPIENT";
//	private static String name = "B110691";

	/**
	 * 给角色添加用户
	 * 
	 * @param self
	 *            obj
	 * @param internal_value
	 *            角色名
	 * @param name
	 *            用户名
	 * @throws WTPropertyVetoException
	 * @throws WTException
	 */
	public static void addPrincipalToRole(WTObject primaryBusinessObject, ObjectReference self)
			throws WTPropertyVetoException, WTException {
		System.out.println(">>>>====================B1 startWith  add role==============<<<");
		if (primaryBusinessObject instanceof WTPart) {
			WTPart part = (WTPart) primaryBusinessObject;
			String viewName = part.getViewName();
			System.out.println("viewName====>>>" + viewName);
			boolean ben = getPartNumbrt(part);
			System.out.println("viewName====>>>" + ben);
			if (ben) {

				WfProcess process = BomWorkFlowUtil.getProcess(self);
				wt.team.Team team = null;
				try {
					team = getTeam(process);
				} catch (Exception ex) {
					ex.printStackTrace();
					throw new WTException(ex);
				}

				PropertiesUtil ut = new PropertiesUtil(configFilePath);
				String PM_User = ut.getValueByKey("BLU.PM_User");
				System.out.println("PM_User=====>>>"+PM_User);
				Role theRole = Role.toRole(internal_value);
				WTUser user = getUserByName(PM_User);
				System.out.println("theRole===" + theRole + "==>>user===>>" + user);
				if (user == null) {
					throw new WTException("没有找到用户: [" + user + "] ");
				} else {
					team.addPrincipal(theRole, user);
				}
				PersistenceHelper.manager.refresh(team);

			}

		}
	}

	// 根据用户名查询WTUser对象
	public static WTUser getUserByName(String username) throws WTException {
		WTUser user = null;
		QuerySpec qs = new QuerySpec(WTUser.class);
		SearchCondition sc = new SearchCondition(WTUser.class, WTUser.NAME, "=", username);
		qs.appendWhere(sc);
		QueryResult qr = PersistenceHelper.manager.find(qs);
		while (qr.hasMoreElements()) {
			user = (WTUser) qr.nextElement();
		}
		return user;
	}

	/**
	 * 根据WfProcess对象，获得团队
	 * 
	 * @param process
	 * @return
	 * @throws Exception
	 */
	public static Team getTeam(WfProcess process) throws Exception {

		Team team = null;
		ReferenceFactory rf = new ReferenceFactory();
		String oid = rf.getReferenceString(process);
		WTObject wtobject = (WTObject) rf.getReference(oid).getObject();
		if (wtobject instanceof TeamManaged) {
			team = (Team) ((TeamManaged) wtobject).getTeamId().getObject();
		} else if (wtobject instanceof Team) {
			team = (Team) wtobject;
		}
		return team;
	}

	/**
	 * 判定料号是否B1开头
	 * 
	 * @param part
	 * @return boolean
	 */
	private static boolean getPartNumbrt(WTPart part) {
		boolean temp = false;
		try {
			String SemiFinishedGoodType = (String) IBAUtil.getIBAValue(part, "SemiFinishedGoodType");
			System.out.println("SemiFinishedGoodType=======>>"+SemiFinishedGoodType);
			if (("B1").equals(SemiFinishedGoodType)) {
				temp = true;
			}
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return temp;
	}

	public static void setUserByPartIba(WTObject obj) {
		try {
			WTPart parts = null;
			if (obj instanceof WTPart) {

				parts = (WTPart) obj;

				WTPart part;

				part = getLatestPart(parts);

				String versionPart = part.getIterationIdentifier().getValue();
				String partCNAndENName = (String) IBAUtil.getIBAValue(part, "partEnvProtectionCategory");
				System.out.println("partNumber===>>" + part.getNumber() + ":====>>>" + partCNAndENName);
				System.out.println("part number===>>" + part.getNumber() + "===>>" + versionPart);

			}
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
	
	public static WTPart getLatestPart(WTPart part) throws WTException {
		View view = (View) part.getView().getObject();
		WTPartConfigSpec configSpec = WTPartConfigSpec
				.newWTPartConfigSpec(WTPartStandardConfigSpec.newWTPartStandardConfigSpec(view, null));
		QueryResult qr = ConfigHelper.service.filteredIterationsOf(part.getMaster(), configSpec);
		return qr.hasMoreElements() ? (WTPart) qr.nextElement() : null;
	}
	

}
